/**
 * Created by Dalyn on 2017/2/28.
 */
import React from "react";
import { hashHistory } from 'react-router';
import Confirm from "../../common/Confirm";
import { Alert } from 'antd';
import { Modal,Icon } from 'antd';
import GetManagerListMutation from "./mutation/GetManagerListMutation"
import UpdateManagerStatusMutation from "./mutation/UpdateManagerStatusMutation"
import ManagerDetailMutation from "./mutation/ManagerDetailMutation"
import Relay from "react-relay";
import Manager_item from "./Manager_item"
import "./css/manager.css";
import ReactKey from "../../util/ReactKey";
import ManagerSet from "./ManagerSet"
import ManagerEdit from "./ManagerEdit"
import Util from "../../util/Util";

/*禁用/启用弹框*/
class Disable extends React.Component{
    constructor(props){
        super(props);
        this.state={
            disable:false,
            managerIds:'',
            status:'',
            text:'',
            newStatus:''
        };
        this.style={
            alert:{
                width:"300px",
                height:"160px",
                margin:"0 auto"
            }
        };
    }
    /*确定修改*/
    handleOk = (e) => {
        if(this.state.managerIds==1){
            alert('超级管理员不可操作');
            this.setState({
                disable: false,
            });
            return;
        }

        Relay.Store.commitUpdate(
            new UpdateManagerStatusMutation({
                managerIds:this.state.managerIds,
                status:this.state.newStatus
            }),
            {
                onFailure: () => {
                },
                onSuccess: (response) => {
                    let errorcode = response.updateManagerStatus.data.errorCode;
                    if(errorcode==0){
                        this.props.managerList();
                    }
                }
            }
        )
        this.setState({
            disable: false,
        });
    }
    /*取消操作*/
    handleCancel = (e) => {
        this.setState({
            disable: false,
        });
    }

    render(){
        return (
            <Modal visible={this.state.disable} onOk={this.handleOk} onCancel={this.handleCancel} style={{width:"440px",height:"270px",display:"block"}}>
                <div className="rolemanage_delate-modal">
                    <Icon type="exclamation-circle" />
                    <span>
                        {this.state.text}
                    </span>
                </div>
            </Modal>
        )
    }
}

/*编辑组件*/
class Edit extends React.Component{
    constructor(props){
        super(props);
        this.state={
            edit:false
        }
        this.style={

        }
    }
    handleOk = (e) => {
        this.setState({
            edit: false,
            pnum:0
        });
    }
    handleCancel = (e) => {
        this.setState({
            edit: false,
        });
    }
    render(){
        return (
            <Modal visible={this.state.edit} onCancel={this.handleCancel} style={{width:"440px",height:"270px",display:"block"}}>
                <span className="manager_duty_tp">财务{this.state.pnum}人</span>
                <textarea style={{rows:5,width:360,height:115,resize:"none",outline:"none",marginTop:30,marginLeft:30,padding:10}}/>
                <span className="manager_duty_cancel" onClick={this.handleCancel}>取消</span>
                <span className="manager_duty_ok" onClick={this.handleOk}>确定</span>
            </Modal>
        )
    }
}

/*导出组件*/
export default class ManagerList extends React.Component{
    constructor(props){
        super(props);
        this.style={
            confirm:{
                width: '96px',
                height: '27px',
                backgroundColor: "#a0d468",
                fontSize: "14px",
                color: "#fff",
                fontFamily: "Microsoft YaHei",
                borderRadius:"3px"
            },
            page_ensure: {
                width: '39px',
                height: '22px',
                backgroundColor: "white",
                border: '1px solid #e7e6e6',
                borderRadius: '2px',
                color: "#999"
            }
        };
        this.state={
            arrgroup:[],
            /*总共多少条*/
            totalResult: "",
            /*每页条数*/
            pageItem: "",
            /*指定页码*/
            pageNum: 1,
            /*指定每页显示条数*/
            pageSize: 10,
        };
        this.group = {};
        this.arrgroup =[];
        this.statusType = {
            "0":"已禁用",
            "1":"已开通",
            "2":"已激活"
        };
        this.managerInfo = [];
    }

    componentWillMount(){
        this.managerList();
    }

    /*查询数据*/
    managerList(){
        this.arrgroup = [];
        Relay.Store.commitUpdate(
            new GetManagerListMutation({
                pageNum: this.state.pageNum,
                pageSize: this.state.pageSize
            }),
            {
                onFailure: () => {
                },
                onSuccess: (response) => {
                    let data = response.getManagerList.data;
                    let errorcode = data.errorCode
                    if(errorcode==0){
                        this.arrgroup = data.managerList;
                        this.setState({
                            arrgroup:this.arrgroup,
                            totalResult: data.totalResult,
                            pageItem: this.arrgroup.length
                        })
                    }
                }
            }
        )
    }

    /**错误提示框*/
    showError(title,value){
        Modal.error({
            title: title,
            content: value,
            width:390
        });
    }

    /*编辑*/
    edit(managerId){
       // this.refs.update.getDefaultPwd();
        //获取人员详情
        this.managerInfo = [];
        Relay.Store.commitUpdate(
            new ManagerDetailMutation({
                managerId: managerId
            }),
            {
                onFailure: () => {
                    showError("系统错误","请稍后再试");
                },
                onSuccess: (response) => {
                    let data = response.managerDetail.data;
                    let errorcode = data.errorCode;
                    if(errorcode==0){
                        this.refs.update.showRole();
                        this.managerInfo = data.manager;
                        this.refs.update.refs._phone.setState({
                            text:data.manager.phone
                        });
                        this.refs.update.refs._name.setState({
                            text:data.manager.name
                        });
                        this.refs.update.newPwd="";
                        this.refs.update.initHit();
                        this.refs.update.setState({
                            managerId:managerId,
                            name: data.manager.name,
                            password: data.manager.password,
                            phone: data.manager.phone,
                            roleId:data.manager.roleId,
                            showPwd:"*********"
                        })
                    }else{
                        this.showError("",data.value);
                    }
                }
            }
        )
    }

    /*添加人员*/
    addManager() {
        this.refs.create.getDefaultPwd();
        this.refs.create.initHit();
        this.refs.create.setState({
            displayflag:true,
        });
    }

    /*更新用户状态*/
    updateStatus(managerId,status){
        this.refs.disable.setState({
            disable:true,
            managerIds:managerId,
            status:status
        })
        if(0 == status){
            this.refs.disable.setState({
                text: "确定要启用此用户吗",
                newStatus:'1'
            });
        }else{
            this.refs.disable.setState({
                text: "确定要禁用此用户吗",
                newStatus:'0'
            });
        }
    }

    /*页码*/
    page() {
        let pageTotal = this.pageTotal();
        let pageNum = this.state.pageNum;
        if (pageNum < 1) {
            this.setState({
                pageNum: 1,
            }, this.managerList)
        }else if (pageNum > pageTotal) {
            this.setState({
                pageNum: pageTotal,
            }, this.managerList)
        } else {
            this.setState({
                pageNum: pageNum,
            }, this.managerList)
        }
    }
    /*总页数*/
    pageTotal() {
        return Math.ceil(this.state.totalResult / this.state.pageSize)
    }

    /*上一页*/
    leftBtn() {
        let pageNum = this.state.pageNum;
        let pageTotal = this.pageTotal();
        if (pageNum <= 1 || pageNum > pageTotal) {
            return;
        } else {
            pageNum--;
            this.setState({
                pageNum: pageNum,
            }, this.managerList)
        }
    }

    /*下一页*/
    rightBtn() {
        let pageTotal = this.pageTotal();
        let pageNum = this.state.pageNum;
        if (pageNum >= pageTotal) {
            return;
        } else {
            pageNum++;
            this.setState({
                pageNum: pageNum,
            }, this.managerList)
        }
    }

    /*页面表单失去焦点时*/
    changePageNum(e){
        let numtest = /^[0-9]*$/;
        let text = e.target.value
        if(!numtest.test(text)){
            return
        }
        this.setState({
            pageNum:text
        });
    }

    /*员工列表*/
    addList(){
        return this.state.arrgroup.map((item,index)=>{
            return(
                <Manager_item item={item} index={index} key={ReactKey.key} edit={this.edit.bind(this)} updateStatus={this.updateStatus.bind(this)}/>
            );
        })
    }


    render(){
        return (
            <div className="manager clear">
                <div className="manager_duty_box" style={{"height":"700px"}}>
                    <div style={!Util.authorityCheck("manager") ? {display: 'none'} :{}}>
                        <Confirm style={this.style.confirm} tcontext={'新增人员'} touch={this.addManager.bind(this)}/>
                    </div>
                    <table className="manager_duty_table  settle_rec_table">
                        <thead>
                            <tr>
                                {
                                    ["用户ID","用户名","手机号","角色","状态","操作"].map((item)=>
                                        <th>
                                            {item}
                                        </th>
                                    )
                                }
                            </tr>
                        </thead>
                        <tbody>
                            {
                                this.addList()
                            }
                        </tbody>
                    </table>
                    <div className="manager_page clear">
                        <ol className="manager_page_ol clear">
                            <li className="manager_page_oli1">总计<span>{this.state.totalResult}</span>条</li>
                            <li className="manager_page_oli2">每页<span>{this.state.pageItem}</span>条</li>
                            <li className="manager_page_oli3">
                                共<span>{this.pageTotal()}</span>页
                            </li>
                            <li>第&nbsp;&nbsp;<input type="text" className="manager_page_olinp" value={this.state.pageNum}
                                                    onChange={this.changePageNum.bind(this)} />&nbsp;&nbsp;页
                            </li>
                            <li><Confirm tcontext={'确定'} style={this.style.page_ensure} touch={this.page.bind(this)}
                                         bluron/>
                            </li>
                            <li className="manager_page_olbtn">
                                <i className="manager_page_button manager_page_left" onClick={this.leftBtn.bind(this)}></i>
                                <i className="manager_page_button manager_page_right" onClick={this.rightBtn.bind(this)}></i>
                            </li>
                        </ol>
                    </div>
                </div>
                <ManagerSet ref={"create"} key={ReactKey.key} managerList={this.managerList.bind(this)} />
                <Disable ref={"disable"} key={ReactKey.key} managerList={this.managerList.bind(this)}/>
                <ManagerEdit ref={"update"} key={ReactKey.key} managerList={this.managerList.bind(this)} />
            </div>
        )
    }
}